package com.sh.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sh.common.ResponseInfoEnum;
import com.sh.common.ReturnVO;
import com.sh.entity.Customer;
import com.sh.entity.Oil;
import com.sh.entity.Repair;
import com.sh.entity.SystemParam;
import com.sh.entity.Tires;
import com.sh.entity.User;
import com.sh.service.CustomerService;
import com.sh.service.RepairService;
import com.sh.service.RptService;
import com.sh.util.DateUtil;
import com.sh.util.ExcelUtil;
import com.sh.util.FileUitl;

import cn.hutool.core.util.NumberUtil;

/**
 * 修理费 相关 controller
 * */
@RestController
@RequestMapping("/api/repair")
public class RepairController extends BaseController{
	@Autowired
	RepairService repairService;

	@Autowired
	CustomerService customerService;


	@Autowired
	RptService rptService;

	@ResponseBody
	@RequestMapping("/listRepair")
	public Object listRepair(
			@RequestParam(value = "startPage",required = false,defaultValue="1") int startPage,
			@RequestParam(value = "pageCount",required = false,defaultValue="100") int pageCount,
			@RequestParam(value = "startDate",required = false) String startDate,
			@RequestParam(value = "endDate",required = false) String endDate,
			@RequestParam(value = "carNum",required = false) String carNum,
			@RequestParam(value = "carOnwer",required = false) String carOnwer,
			@RequestParam(value = "customerName",required = false) String customerName){


		User user = null;
		String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");

		Map<String,Object> conMap = new HashMap<String,Object>();
		conMap.put("startDate",startDate);
		conMap.put("endDate", endDate);
		conMap.put("carNum", carNum);
		conMap.put("carOnwer", carOnwer);
		conMap.put("customerName", customerName);

		//分页 开始  //返回数量  pageCount
		int start = (startPage-1)*pageCount;

		conMap.put("start", start);
		conMap.put("pageCount", pageCount);

		int count =
				repairService.listRepairCount(conMap,user,sysTime);


		List<Repair> list =
				repairService.listRepair(conMap,user,sysTime);

		return succForPage(ResponseInfoEnum.REPAIR_QUERY_SUCCESS, list,0);

	}

	//上传 excel文件,并且到DB
	@ResponseBody
	@RequestMapping("/uploadRepair")
	public ReturnVO uploadRepair(MultipartFile file){

		User user = new User();
		SystemParam rootNode = null;
		try {
			if(!file.isEmpty()){
				String path = FileUitl.createFile(file,serverPath);
				List<List<Object>> list =
						ExcelUtil.readExcelFirstSheet(path);


				//验证 数据中是不是存在 结转数据
				String carryMsg = checkCarryData(list);
				if(!"".equals(carryMsg)){
					return failForService("400", ResponseInfoEnum.REPAIR_UPLOAD_FAILED,carryMsg);
				}


				//检验数据的准确性，并转换为  List<Object> 格式
				Map<String,Object> map =
						checkDataAndToBO(list,"1");

				String msg = (String)map.get("msg");
				if("".equals(msg)){
					//没有错误继续执行下面步骤
					List<Repair> checkList = (List<Repair>)map.get("list");
					String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");
					String rntMsg =
							repairService.saveUpload(checkList,user,sysTime);
				}else{
					//有错误
					return failForService("400", ResponseInfoEnum.REPAIR_UPLOAD_FAILED,msg);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("读取文件错误:",e);
			return failForService("400", ResponseInfoEnum.REPAIR_UPLOAD_FAILED,e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("上传文件错误:",e);
			return failForService("400", ResponseInfoEnum.REPAIR_UPLOAD_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.REPAIR_UPLOAD_SUCCESS, null);

	}

	/**
	 * 上传的数据 验证 是不是包含 已经结转的数据
	 * */
	private String checkCarryData(List<List<Object>> list) {
		// TODO Auto-generated method stub

		//验证 需要修改的数据 是不是已经 结转
		List<String> yearList = new ArrayList<>();

		String yearTmp = "";
		for(int i=0;i<list.size();i++){
			List<Object> listTmp = list.get(i);
			yearTmp = (String)listTmp.get(0);
			if(DateUtil.checkDateFormat(yearTmp,"yyyy-MM-dd")){
				if(!yearList.contains(yearTmp)){
					yearList.add(yearTmp.split("-")[0]);
				}
			}
		}
		String checkDataCarryMsg =
				rptService.checkDataCarry(yearList);

		return checkDataCarryMsg;
	}

	//检验数据的准确性，并转换为  List<Stone> 格式
	//String isCheckRepeat 是不是需要重复性验证
	private Map<String,Object> checkDataAndToBO(List<List<Object>> list,String isCheckRepeat) {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String,Object>();


		StringBuffer sb = new StringBuffer();
		sb.append("");
		List<Repair> objList = new ArrayList<Repair>();
		for(int i=0;i<list.size();i++){
			List<Object> listTmp = list.get(i);
			Repair obj = new Repair();
			//日期
			obj.setRepairDate((String)listTmp.get(0));
			//客户名称
			obj.setCustomerName((String)listTmp.get(1));
			//车牌号
			obj.setCarNum((String)listTmp.get(2));
			//修理明细
			obj.setRepairDetail((String)listTmp.get(3));
			//单价
			obj.setUnitPrice((String)listTmp.get(4));
			//数量
			obj.setCount((String)listTmp.get(5));
			//金额
			obj.setAmount((String)listTmp.get(6));
			//备注
			obj.setRemark((String)listTmp.get(7));
			//付款状态
			obj.setPayStatus((String)listTmp.get(8));
			//发票号码
			obj.setInvoiceNum((String)listTmp.get(9));
			//车主
			obj.setCarOwner((String)listTmp.get(10));

			String msg = checkData(obj,isCheckRepeat);
			if(!"".equals(msg)){
				sb.append("第 "+(i+1)+"行数据："+msg + "\n");
			}

			objList.add(obj);
		}

		map.put("msg", sb.toString());
		map.put("list", objList);
		return map;
	}

	/**
	 * 批量 删除 修理信息
	 * 删除之前需要 进行 数据验证是不是 当年数据，如果是当前数据，才能修改
	 * */
	@ResponseBody
	@RequestMapping("/deleteRepairs")
	public ReturnVO deleteRepairs(
			@RequestParam(value = "tableSelectedIds",required = false) String tableSelectedIds
	){

		User user = getLoginUser();
		try {

			if(tableSelectedIds!=null){
				String[] ids = tableSelectedIds.split(",");

				//验证 需要删除的ID对应的数据 是不是 已经 结转
				List<String> yearList =
						repairService.listYearByIds(ids);
				String carryMsg =
						rptService.checkDataCarry(yearList);
				if(!"".equals(carryMsg)){
					return failForService("400", ResponseInfoEnum.REPAIR_DELETE_FAILED,carryMsg);
				}


				repairService.deleteRepairs(ids);
			}


		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("删除 错误:",e);
			return failForService("400", ResponseInfoEnum.REPAIR_DELETE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.REPAIR_DELETE_SUCCESS, null);

	}

	/**
	 * 新增 / 修改 保存数据
	 * */
	@ResponseBody
	@RequestMapping("/saveRepairs")
	public ReturnVO saveRepairs(
			Repair repair
	){

		User user = getLoginUser();
		try {
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("repair", repair);
			conMap.put("user", user);

			//验证 是不是已经结转的数据
			List<String> yearList = new ArrayList<>();
			if(repair.getId()==null||
					"".equals(repair.getId())){
				//如果新增
				if(DateUtil.checkDateFormat(
						repair.getRepairDate(), "yyyy-MM-dd")){
					yearList.add(repair.getRepairDate().split("-")[0]);

				}
			}else{
				//如果是修改数据，需要查询修改的数据是不是  结转
				String[] ids = {repair.getId()};
				yearList =
						repairService.listYearByIds(ids);
				//判断修改后 数据是不是 结转
				if(DateUtil.checkDateFormat(
						repair.getRepairDate(), "yyyy-MM-dd")){
					if(!yearList.contains(repair.getRepairDate().split("-")[0]))
						yearList.add(repair.getRepairDate().split("-")[0]);
				}
			}
			String carryMsg =
					rptService.checkDataCarry(yearList);
			if(!"".equals(carryMsg)){
				return failForService("400", ResponseInfoEnum.REPAIR_SAVE_FAILED,carryMsg);
			}



			//添加验证
			String msg = checkData(repair,"1");
			if(!"".equals(msg)){
				return failForService("400", ResponseInfoEnum.REPAIR_SAVE_FAILED,msg);
			}

			repairService.saveRepairs(repair,user);


		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("保存 错误:",e);
			return failForService("400", ResponseInfoEnum.REPAIR_SAVE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.REPAIR_SAVE_SUCCESS, null);

	}
	//添加验证
	//String isCheckRepeat 是不是需要重复性验证
	private String checkData(Repair repair,String isCheckRepeat) {
		// TODO Auto-generated method stub

		StringBuffer msg = new StringBuffer();
		msg.append("");

		//客户名称 不能为空
		if("".equals(repair.getCustomerName())){
			msg.append("【客户名】不能为空! ");
		}else{
			//判断 客户名称有么有存在
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("customerName",repair.getCustomerName());
			List<Customer> customerList =
					customerService.listCustomerByName(conMap);
			if(customerList==null ||
					customerList.size()==0){
				msg.append("【客户名】不存在，请先维护客户信息! ");
			}
		}

		//判断 日期
		if("".equals(repair.getRepairDate())){
			msg.append("【日期】不能为空! ");
		}

		//判断 车牌号
		if("".equals(repair.getCarNum())){
			msg.append("【车牌号】不能为空! ");
		}

		//判断 单价
		if("".equals(repair.getUnitPrice())){
			msg.append("【单价】不能为空! ");
		}else{
			if(!NumberUtil.isNumber(repair.getUnitPrice())){
				msg.append("【单价】只能为 数字! ");
			}
		}
		//判断 数量
		if("".equals(repair.getCount())){
			msg.append("【数量】不能为空! ");
		}else{
			if(!NumberUtil.isNumber(repair.getCount())){
				msg.append("【数量】只能为 数字! ");
			}
		}
		//判断 金额
		if("".equals(repair.getAmount())){
			msg.append("【金额】不能为空! ");
		}else{
			if(!NumberUtil.isNumber(repair.getAmount())){
				msg.append("【金额】只能为 数字! ");
			}
		}

		//车主 不能为空
		if("".equals(repair.getCarOwner())){
			msg.append("【车主】不能为空! ");
		}else{
			//判断 车主有么有存在
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("customerName",repair.getCarOwner());
			List<Customer> customerList =
					customerService.listCustomerByName(conMap);
			if(customerList==null ||
					customerList.size()==0){
				msg.append("【车主】不存在，请先维护客户信息! ");
			}
		}


		if("1".equals(isCheckRepeat)){
			//判断 数据是不是已经存在
			//根据 【日期】【车号】【客户名】【金额】判断
			boolean flag =
					repairService.isRepairExist(repair);
			if(flag){
				msg.append("相同  记录已经存在! ");
			}
		}


		return msg.toString();
	}
}
